package znet

import (
	"errors"
	"fmt"
	"gitee.com/MrDaiM/zinx/ziface"
	"sync"
)

/*
	ConManager 链接管理模块
*/
type ConnManager struct {
	connections map[uint32]ziface.IConnection // 管理的链接信息
	connLock    sync.RWMutex                  // 读写链接的读写锁

}

/*
	NewConnManager 新创建一个连接管理
*/
func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]ziface.IConnection),
	}
}


/*
	Add 添加链接
*/
func (connMgr *ConnManager) Add(conn ziface.IConnection) {
	// 保护共享资源Map 加写锁
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()
	connMgr.connections[conn.GetConnId()] = conn
	fmt.Print("connection add to ConnManager successfully: conn num = ", connMgr.Len())
}

/*
	删除链接 Remove
*/
func (connMgr *ConnManager) Remove(conn ziface.IConnection) {
	// 保护共享资源Map 加写锁
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	// 删除conn链接
	delete(connMgr.connections, conn.GetConnId())

	fmt.Println("connection Remove ConnId = ", conn.GetConnId(), " successfull:conn num", connMgr.Len())
}

/*
	利用ConnID获取连接
*/
func (connMgr *ConnManager) Get(connID uint32) (ziface.IConnection, error) {
	// 保护共享资源，加读锁
	connMgr.connLock.RLock()
	defer connMgr.connLock.Unlock()

	// 获取conn链接
	if conn, ok := connMgr.connections[connID]; ok  {
		return conn, nil
	} else {
		return nil, errors.New("connection not found")
	}
}

/*
	获取当前链接容量
*/
func (connMgr *ConnManager) Len() int {
	return len(connMgr.connections)
}

// ClearConn 删除并停止所有链接
func (connMgr *ConnManager) ClearConn() {
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()
	for connID, conn := range connMgr.connections{
		// 停止
		conn.Stop()
		// 删除
		delete(connMgr.connections, connID)
	}
	fmt.Println("Clear All Connections successfully: conn num = ", connMgr.Len())

}
